<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 服务时长log
 */

class VolunteerServiceTimeLog extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;


    protected $table = 'volunteer_service_time_log';

    /**
     * 获取服务时长列表
     * @param user_id
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     * @param start_time   开始时间
     * @param end_time  结束时间
     * @param keywords  筛选内容
     */
    public function lists($user_id, $keywords = null, $start_time = null, $end_time = null, $limit = 10)
    {
        $res = $this->from($this->getTable() . ' as l')->select('l.id', 'l.service_time', 'l.type', 'l.intro', 'l.create_time', 'u.volunteer_service_time')
            ->join('user_info as u', 'u.id', '=', 'l.user_id')
            ->where(function ($query) use ($user_id, $start_time, $end_time) {
                if ($user_id) {
                    $query->where('l.user_id', $user_id);
                }

                if ($start_time && $end_time) {
                    $query->whereBetween('l.create_time', [$start_time, $end_time]);
                }
            })->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('l.intro','like', "%$keywords%");
                }
            })->orderByDesc('l.id')
            ->paginate($limit)
            ->toArray();

        return $res;
    }



    /**
     * 获取服务时长详情
     * @param id 服务时长id
     */
    public function detail($id)
    {
        $res = $this->select('id', 'service_time', 'type', 'intro', 'create_time')
            ->where('id', $id)
            ->first();

        return $res;
    }
}
